import { computed } from 'vue'
import { useUpdateCommodityType } from '../../param-set/commodity-set'
import { useUpdateNetworkType } from '../../param-set/network-set'
import { useUpdateOrderType } from '../../param-set/order-set'
import { UpdateTypeForm } from './types'

const {
  updateCommodityTypeForm,
  updateCommodityTypeLoading,
  updateCommodityType,
  resetUpdateCommodityTypeForm,
} = useUpdateCommodityType()

const {
  updateNetworkTypeForm,
  updateNetworkTypeLoading,
  updateNetworkType,
  resetUpdateNetworkTypeForm,
} = useUpdateNetworkType()

const { updateOrderTypeForm, updateOrderTypeLoading, updateOrderType, resetUpdateOrderTypeForm } =
  useUpdateOrderType()

export default (type: 'commodity' | 'network' | 'order') => {
  const formMap = {
    commodity: updateCommodityTypeForm,
    network: updateNetworkTypeForm,
    order: updateOrderTypeForm,
  }

  const form: UpdateTypeForm = formMap[type]

  const loading = computed(() => {
    return (
      updateCommodityTypeLoading.value ||
      updateNetworkTypeLoading.value ||
      updateOrderTypeLoading.value
    )
  })

  const submit = async (orderModuleId?: string) => {
    if (type === 'commodity') {
      return await updateCommodityType()
    }

    if (type === 'network') {
      return await updateNetworkType()
    }

    if (type === 'order') {
      return await updateOrderType(orderModuleId)
    }
  }

  const resetForm = () => {
    switch (type) {
      case 'commodity':
        resetUpdateCommodityTypeForm()
        break
      case 'network':
        resetUpdateNetworkTypeForm()
        break
      case 'order':
        resetUpdateOrderTypeForm()
        break
    }
  }

  return {
    form,
    loading,
    submit,
    resetForm,
  }
}
